﻿using System.Configuration;

namespace XwOa
{
    internal class ConfigAppSettings
    {
        private static Configuration _config =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        /// <summary>
        ///     写入值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetValue(string key, string value)
        {
            if (_config.AppSettings.Settings[key] == null)
            {
                _config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                _config.AppSettings.Settings[key].Value = value;
            }

            try
            {
                _config.Save();
            }
            catch (ConfigurationErrorsException)
            {
                _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                SetValue(key, value);
            }
        }

        /// <summary>
        ///     读取指定key的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            KeyValueConfigurationElement keyValue = _config.AppSettings.Settings[key];
            return keyValue == null ? "" : keyValue.Value;
        }
    }
}